<style lang="scss" scoped>
  .project-upload-container{
    width:100%;
    float: left;
    height:auto;
    display: block;
  }

  .wrapper{
    height: 50px;
  }

  .fontSize{
    font-family: '微软雅黑';
    font-size: 24px;
    color: #777;
  }

  .upload-title{
    @extend .fontSize;
    float: left;
    margin-top:8px;
  }

  .upload-icon{
    vertical-align: middle;
    display: inline-block;
    width:30px;
    height: 30px;
    background-size:cover;
    background-image: url("../../../assets/images/arrow-toggle.png");
    margin:10px 15px;
    float: left;
    cursor: pointer;
    &.is-opened{
      transform:rotate(-180deg);
    }
  }

  .open-animation{
    transition: all ease-in-out 0.3s;
  }

  .upload-input{
    width:100%;
    height: 0px;
    box-sizing: border-box;
    background: white;
    border-radius: 5px;
    box-shadow: 0px 0px 10px rgba(0,0,0,0.3);
    margin-top: 10px;
    position: relative;
    display: none;
  }

  .unfold-container{
    height: 150px;
    padding: 10px;
    display: block;
  }

  .icon-wrapper{
    width:100px;
    height: 100px;
    display: block;
    text-align: center;
    position: relative;
    float: left;

    .icon-style{
      width:40px;
      height: 40px;
      display: inline-block;
      margin:10px 30px;
      background-size: cover;
    }


    .icon-img{

      @extend  .icon-style;

      background-image: url("../../../assets/images/add.png");

    }

    .icon-document{
      @extend  .icon-style;

      background-image: url("../../../assets/images/document.png");
    }

    .icon-video{
      @extend  .icon-style;
      background-image: url("../../../assets/images/video.png");
    }

    .icon-image{
      @extend  .icon-style;
      background-image: url("../../../assets/images/image.png");
    }

    .icon-text{
      display: inline-block;
      font-family: '微软雅黑';
      color: #777;
      font-size: 16px;
      width:80px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .icon-remove{
      width:15px;
      height: 15px;
      background-image: url("../../../assets/images/close.png");
      background-size: cover;
      display: block;
      position: absolute;
      top:5px;
      right: 10px;
      border-radius: 50%;
      cursor: pointer;
    }

    .upload-input{
      position: absolute;
      left:0;
      top:0;
      width:100%;
      height:100%;
      display: block;
      z-index:1;
      opacity:0;
      cursor: pointer;
    }

  }


  .desc-bottom-text{
    position: absolute;
    bottom:10px;
    left:10px;
    font-size: 14px;
    font-family: '微软雅黑';
    color: #777;
  }

  .upload-tips{
    display: inline-block;
    float:left;
    @extend  .icon-style;
    height: 50px;
    line-height: 50px;
    color:#777;
    margin-left: 10px;
  }

</style>

<template>
  <div class="project-upload-container">
    <div class="wrapper">
      <span class="upload-title">{{loadMsg}}</span>
      <span class="upload-icon open-animation" :class="{'is-opened':show}" @click="toggle"></span>
      <span class="upload-tips" v-if="isEmpty">{{tips}}</span>
    </div>
    <div class="upload-input open-animation" :class="{'unfold-container':show}">
      <div class="icon-wrapper" v-for="(file,index) in files">
        <span :class="'icon-'+getExtensions(index)"></span>
        <span class="icon-text" :title="file.name||file.file_name">{{file.name||file.file_name}}</span>
        <i class="icon-remove" @click="removeItem(index)"></i>
      </div>
      <div class="icon-wrapper">
        <span class="icon-img"></span>
        <span class="icon-text">新增</span>
        <input class="upload-input" name="files" @change="doUpload($event)" type="file" />
      </div>
      <span class="desc-bottom-text">{{innerText}}</span>
    </div>
  </div>
</template>

<script>

  import { IMAGE_FORMAT,VIDEO_FORMAT,DOCUMENT_FORMAT } from  "@/conf/extension";

  import { mapState } from 'vuex';

  export default{
    name:"ContractUpload",
    props:{
      tips:{
        type:String,
        required:false,
        default:''
      },
      loadMsg:{
        type:String,
        required:false,
        default:'上传附件'
      },
      innerText:{
        type:String,
        default:"施工设计图表，合同等文件的word或pdf文档"
      },
      formatRestrict:{
        type:String,
        default:'DOCUMENT'
      },
      exsits:{
        type: Array,
        default () {
          return []
        }
      }
    },
    data(){
      return {
        show: false,
        inited:false,
        FORMAT: {
          IMAGE: [],
          VIDEO: [],
          DOCUMENT:[]
        },
        docType:["DOCUMENT"],
        files:[]
      };
    },
    beforeMount(){

      this.docType = this.formatRestrict.split(',')
      var imgArr=IMAGE_FORMAT.split(',');

      for (var i=0;i<imgArr.length;i++){
        this.FORMAT['IMAGE'].push(imgArr[i]);
      }

      var videoArr=VIDEO_FORMAT.split(',');

      for (var i=0;i<videoArr.length;i++){
        this.FORMAT['VIDEO'].push(videoArr[i]);
      }

      var docArr=DOCUMENT_FORMAT.split(',');

      for (var i=0;i<docArr.length;i++){
        this.FORMAT['DOCUMENT'].push(docArr[i]);
      }

    },
    beforeUpdate(){

      if (!this.inited){

        for (var i=0;i<this.exsits.length;i++){

           this.files.push(this.exsits[i]);

        }

        this.inited=true;

      }
    },
    computed:{
      isEmpty(){
        return this.tips.replace(/(^\s*)|(\s*$)/g,'')!=='';
      },
      ...mapState({
        user:state => state.user.userData,
      })
    },
    methods:{
      toggle(){
        this.show=!this.show;
      },
      removeItem(index,flag){

        var id=this.files[index].id;

        /**
         * 说明是已经存在的文件
         */
        if (this.files[index].file_name!=undefined){
          //告诉外界，我把这个东西删了是 已经存在的文件
          this.$emit('onDeleteExsit',{id});
        }
        else {
          //不存在的文件
          this.$emit('onDelete',{id});

        }



        this.$store.dispatch('doDeleteFile',{
          id:id,
          token:this.user.token
        }).then(response =>{

          if(response.status==200&&response.statusText=="OK"&&response.data){

            this.$message("文件删除成功!");

          }
          else {
            this.$message("文件已删除或文件不存在!");
          }

        },response =>{

          this.$message("文件删除失败!"+response.data);

        }).catch(err => {

          this.$message("系统错误，文件删除失败，错误信息:"+err);

        });

        this.files.splice(index,1);

      },
      isSpecificType(type,extension){
        var str=extension.toLowerCase();
        var flag=false;
        if (typeof type === 'string') {
          for(var i=0;i<this.FORMAT[type].length;i++){

            if (str.lastIndexOf(this.FORMAT[type][i])>=0){
              flag=true;
              break;
            }
          }
          return flag;
        } else {
          type.every(t => {
            this.FORMAT[t].every(item => {
              if (str.lastIndexOf(item) >= 0) {
                flag = true
                return false
              }
              return true
            })
            if (flag) {
              return false
            }
            return true
          })
          return flag
        }
      },
      getExtensions(index){

        //这儿这样写的原因是已经有的文件，后台返回的是{"file_name":文件}这样的;

        var target=this.files[index].name||this.files[index].file_name;

        var result='';

        //判断文件的显示类型
        //图片类型
        if (this.isSpecificType('IMAGE',target)){
          result='image';
        }
        //视频类型
        else if (this.isSpecificType('VIDEO',target)){
          result='video';
        }
        //文档类型
        else if(this.isSpecificType('DOCUMENT',target)){
          result='document';
        }
        else {
          result='document';
        }

        return result;

      },
      doUpload($event){

        var target=$event.target;

        var files=target.files;

        var flag=false;

        var formData=new FormData();

        for(var i=0;i<files.length;i++){
          if (this.isSpecificType(this.docType,files[i].name))
          {

            this.files.push(files[i]);

            formData.append('file',files[i]);

          }
          else {
            flag=true;
          }
        }

        if (flag){
          this.$message('系统只保存了您选择的符合上传要求的文件类型，其它类型的文件已自动忽略');
        }

        target.value="";

        /**
         * TODO
         */

        this.$store.dispatch('doLoadFile',{ data:formData,token:this.user.token}).then((response)=>{

          if (response.status==200&&response.statusText=="OK"){

            this.reportFileInfo(response.data);

            this.$set(this.files[this.files.length-1],'id',response.data.data.id);

           //备注 这儿只是一个hack方案，因为我本来要做成多文件上传的，结果成了单文件上传，所以需要改的永远的是最后一个

          }

        },(response)=>{

          this.$message('上传文件失败，失败原因:'+response.data);

        }).catch(err=>{

          this.$message('上传文件出错，错误信息:'+err);

        });
      },
      reportFileInfo(data){

        this.$emit('loadedFile',data);

      }
    }
  }
</script>
